﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Globalization;

using Angerona.Model;

namespace Angerona.Views
{
    public partial class AddMaintenance : PhoneApplicationPage
    {
        DateTime defaultDate = new DateTime(2013, 1, 1);

        public AddMaintenance()
        {
            InitializeComponent();
            ApplicationBarInitializer();
            
            this.maintenanceDate.Value = defaultDate;
            //this.maintenanceDate.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
        }

        private void ApplicationBarInitializer()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;
            // add button
            ApplicationBarIconButton btn_add = new ApplicationBarIconButton();
            btn_add.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_add.Text = AngeronaLang.add;
            ApplicationBar.Buttons.Add(btn_add);
            btn_add.Click += new EventHandler(addMaintenanceOperation);

            ApplicationBarIconButton btn_cancel = new ApplicationBarIconButton();
            btn_cancel.IconUri = new Uri("Img/appbar_cancel.png", UriKind.Relative);
            btn_cancel.Text = AngeronaLang.cancel;
            ApplicationBar.Buttons.Add(btn_cancel);
            btn_cancel.Click += new EventHandler(CancelOperation);
        }

        /// <summary>
        /// Saves the idOfCar
        /// </summary>
        int idOfCar;

        /// <summary>
        /// Overrided method: When the user navigates here, the page try to get the id of the car.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string ID;
            if (NavigationContext.QueryString.TryGetValue("ID", out ID))
                idOfCar = Convert.ToInt32(ID);
            base.OnNavigatedTo(e);
        }

        /// <summary>
        /// Converts into floats the strings passed
        /// </summary>
        /// <param name="inputNumber">the string to be parsed or setted as default 0</param>
        /// <returns></returns>
        private float ConvertFloatOrDefault(string inputNumber)
        {
            if (inputNumber == "")
                return 0;
            else
                return Convert.ToSingle(inputNumber);
        }

        private void addMaintenanceOperation(object sender, EventArgs e)
        {
            MaintenanceData operation = new MaintenanceData
            {
                Spent = ConvertFloatOrDefault(convertNumericInput(boxAddCostMaintenance.Text)),
                Vehicle = App.ViewModel.getElementWithID(idOfCar),
                OperationNote = boxNoteMaintenance.Text,
                OperationDate = CheckAgeOrDefault((DateTime)maintenanceDate.Value),
            };

            App.ViewModel.AddMaintenance(operation);
            NavigationService.GoBack();
        }

        private void CancelOperation(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        //// Check Date if not too old
        private DateTime CheckAgeOrDefault(DateTime x)
        {
            DateTime temp = new DateTime(1754, 1, 1);
            if (x < temp)
            {
                MessageBox.Show(AngeronaLang.ReminderToOldDate, AngeronaLang.Error, MessageBoxButton.OK);
                x = defaultDate;
            }
            return x;
        }

        private string convertNumericInput(string stringToCheck)
        {
            if (CultureInfo.CurrentCulture.Name == "it-IT")
            {
                char[] arrayToCheck = stringToCheck.ToArray();
                for (int i = 0; i < stringToCheck.Length; i++)
                    if (arrayToCheck[i] == '.')
                        arrayToCheck[i] = ',';

                string newText = new string(arrayToCheck);
                return newText;
            }
            else 
                return stringToCheck;
        }
    }
}